#include <stdio.h>
#include <stdlib.h>
#include <gl\glut.h>
#include <Windows.h>
#include <conio.h>
#include "chip8.h"

Chip8 chip8;

void gotoxy(HANDLE hOut, int x, int y)
{
	COORD pos = {
		x, y
	};
	SetConsoleCursorPosition(hOut, pos);
}

void dokeys(char key)
{
	switch(key) {
	case '1':
		chip8.key[0x1] = !chip8.key[0x1]; break;
	case '2':
		chip8.key[0x2] = !chip8.key[0x2]; break;
	case '3':
		chip8.key[0x3] = !chip8.key[0x3]; break;
	case '4':
		chip8.key[0xC] = !chip8.key[0xC]; break;
	case 'q':
		chip8.key[0x4] = !chip8.key[0x4]; break;
	case 'w':
		chip8.key[0x5] = !chip8.key[0x5]; break;
	case 'e':
		chip8.key[0x6] = !chip8.key[0x6]; break;
	case 'r':
		chip8.key[0xD] = !chip8.key[0xD]; break;
	case 'a':
		chip8.key[0x7] = !chip8.key[0x7]; break;
	case 's':
		chip8.key[0x8] = !chip8.key[0x8]; break;
	case 'd':
		chip8.key[0x9] = !chip8.key[0x9]; break;
	case 'f':
		chip8.key[0xE] = !chip8.key[0xE]; break;
	case 'z':
		chip8.key[0xA] = !chip8.key[0xA]; break;
	case 'x':
		chip8.key[0x0] = !chip8.key[0x0]; break;
	case 'c':
		chip8.key[0xB] = !chip8.key[0xB]; break;
	case 'v':
		chip8.key[0xF] = !chip8.key[0xF]; break;
	}
}

int main(int argc, char* argv[])
{
	chip8.loadApplication(argv[1]);
	system("cls");
	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); 
	while(true)
	{
		gotoxy(hOut, 0, 0);
		while(_kbhit()) {
			dokeys(_getch());
		}
		chip8.emulateCycle();
		if(chip8.drawFlag) {
			for(int i = 0; i < 32; ++i) {
				for(int j = 0; j < 64; ++j) {
					if(chip8.gfx[i*64+j] == 0) {
						printf(" ");
					} else {
						printf("#");
					}
				}
				printf("\n");
			}
			chip8.drawFlag = false;
		}
	}
}
